// custom-tab-bar/index.js
import { list } from './data'
import { getElementRect } from '../utils/common'
Component({
  options: {
    styleIsolation: 'shared'
  },
  /**
   * 组件的属性列表
   */
  properties: {},

  /**
   * 组件的初始数据
   */
  data: {
    active: 0,
    list: list
  },
  lifetimes: {
    async ready() {
      const navBarRect = await getElementRect('.tabbar-item', true, this)
      const { screenHeight, safeArea } = wx.getSystemInfoSync()
      const tabBarHeight = screenHeight - safeArea.bottom + navBarRect.height
      wx.setStorageSync('tabBarHeight', tabBarHeight)
    }
  },

  /**
   * 组件的方法列表
   */
  methods: {
    onChange(event) {
      // event.detail 的值为当前选中项的索引
      this.setData({ active: event.detail })
      wx.switchTab({
        url: this.data.list[event.detail].path.startsWith('/')
          ? this.data.list[event.detail].path
          : `/${this.data.list[event.detail].path}`
      })
    },
    init() {
      const page = getCurrentPages().pop()
      const route = page ? page.route.split('?')[0] : ''
      const active = this.data.list.findIndex(
        (item) => (item.path.startsWith('/') ? item.path.substr(1) : item.path) === `${route}`
      )
      this.setData({ active })
    }
  }
})
